package com.wclass.controller.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wclass.common.HttpRequest;
import com.wclass.common.ReturnObject;
import com.wclass.entity.BaseAppUser;
import com.wclass.entity.BaseUserFriend;
import com.wclass.entity.CouresOrder;
import com.wclass.entity.CourseInfo;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.model.UserMobile;
import com.wclass.service.IBaseAppUserService;
import com.wclass.service.IBaseUserFriendService;
import com.wclass.service.ICouresOrderService;
import com.wclass.service.ICourseInfoService;
import io.rong.RongCloud;
import io.rong.models.Result;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author 张浩高
 * @since 2018-12-20
 */
@Api(description = "聊天管理")
@RestController
@RequestMapping("/chatRoom")
public class BaseChatRoomController {

    private static Logger logger = LoggerFactory.getLogger(BaseChatRoomController.class);

    /**
     * 融云
     */
    @Value("${rong.appKey}")
    private String appKey;
    /**
     * 融云
     */
    @Value("${rong.appSecret}")
    private String appSecret;

    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private ICouresOrderService orderService;
    @Autowired
    private ICourseInfoService courseInfoService;
    @Autowired
    private IBaseUserFriendService iBaseUserFriendService;

    @ApiOperation("获取全部群分页")
    @RequestMapping(value = "/getMyGroupPage", method = RequestMethod.POST)
    public ReturnObject getMyGroupPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                       @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                       @ApiParam("类型，1：学生端，2：教师端") @RequestParam(defaultValue = "2") Integer type) {
        try {
            EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
            if (type == 1) {
                ew.eq("courseOrder.pay_state", 1);
                ew.eq("courseOrder.pay_person_id", BaseContextHandler.getUserID());
                ew.eq("courseOrder.group_state", 0);
            } else {
                ew.eq("info.user_id", BaseContextHandler.getUserID());
            }
            ew.isNotNull("courseOrder.id");
            ew.eq("info.group_state", "0");
            ew.groupBy("info.id");
            Page<CourseInfo> obj = courseInfoService.selectCourseWithOrderPage(new Page<>(offset, limit), ew);

            List<Map<String, Object>> list = Lists.newArrayList();
            for (CourseInfo info : obj.getRecords()) {
                Map<String, Object> map = Maps.newHashMap();

                map.put("groupId", info.getId());
                map.put("groupName", info.getName());
                map.put("logo", info.getCoverImgUrl());
                map.put("introduce", info.getIntroduce());
                list.add(map);
            }
            return new ReturnObject(0, "请求成功", obj.getTotal(), obj.getPages(), list);
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnObject(12, "系统偷懒了");
        }
    }

    @ApiOperation("编辑群公告")
    @RequestMapping(value = "/editGroup", method = RequestMethod.POST)
    public ReturnObject editGroup(@ApiParam("群id") @RequestParam Long groupId,
                                  @ApiParam("简介") @RequestParam String introduce) {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!judgeHasAdminAuth(BaseContextHandler.getUserID(), info)) {
            return new ReturnObject(1, "没有编辑公告权限");
        }
        info.setIntroduce(introduce);
        courseInfoService.updateById(info);

        return new ReturnObject(0, "编辑成功");
    }

    /**
     * 判断用户群权限
     * @return
     */
    public boolean judgeHasAdminAuth(Long loginUserId, CourseInfo info){
        if (!info.getCrtUserId().equals(loginUserId) && !info.getUserId().equals(loginUserId)) {
            if (info.getAssistant() != null){
                int noEqualNum = 0;
                JSONArray assistantArr = JSONArray.parseArray(info.getAssistant());
                for (int i = 0;i < assistantArr.size();i++) {
                    Long assistantId = assistantArr.getJSONObject(i).getLong("id");
                    if (!assistantId.equals(loginUserId)) {
                        ++noEqualNum;
                    }
                }
                if (noEqualNum == assistantArr.size()) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    @ApiOperation("获取群详情")
    @RequestMapping(value = "/getGroupInfo", method = RequestMethod.POST)
    public ReturnObject<CourseInfo> getGroupInfo(@ApiParam("群id") @RequestParam Long groupId){
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }

        CourseInfo record = new CourseInfo();
        record.setId(groupId);
        record.setClassName(info.getClassName());
        record.setIntroduce(info.getIntroduce());
        record.setBanState(info.getBanState());
        return new ReturnObject<>(0, "", record);
    }

    @ApiOperation("获取群成员列表")
    @RequestMapping(value = "/getGroupUserPage", method = RequestMethod.POST)
    public ReturnObject<Object> getGroupUserPage(@ApiParam("群id") @RequestParam Long groupId) {
        Map<String, Object> ret = Maps.newHashMap();
        CourseInfo courseInfo = courseInfoService.selectById(groupId);
        if (courseInfo == null || courseInfo.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }

        EntityWrapper<CouresOrder> ew = new EntityWrapper<>();
        ew.eq("info.course_info_id", groupId).eq("info.group_state", 0).orderBy("info.course_identity", false);
        List<CouresOrder> orderList = orderService.selectList(ew);

        List<UserMobile> list = Lists.newArrayList();

        int groupIdentity = 2;
        //群主
        BaseAppUser groupOwner = iBaseAppUserService.selectById(courseInfo.getCrtUserId());
        groupOwner.setPassword(null);
        UserMobile groupOwnerMobile = new UserMobile();
        BeanUtils.copyProperties(groupOwner, groupOwnerMobile);
        groupOwnerMobile.setPosition(0);
        list.add(groupOwnerMobile);
        if (courseInfo.getCrtUserId().equals(BaseContextHandler.getUserID())) {
            groupIdentity = 0;
        }
        //管理员：教师、助教
        if (!courseInfo.getCrtUserId().equals(courseInfo.getUserId())){
            BaseAppUser teacher = iBaseAppUserService.selectById(courseInfo.getUserId());
            teacher.setPassword(null);
            UserMobile teacherMobile = new UserMobile();
            BeanUtils.copyProperties(teacher, teacherMobile);
            teacherMobile.setPosition(1);
            list.add(teacherMobile);
            if (courseInfo.getUserId().equals(BaseContextHandler.getUserID()) && groupIdentity != 0) {
                groupIdentity = 1;
            }
        }
        if (courseInfo.getAssistant() != null){
            JSONArray assistantArr = JSONArray.parseArray(courseInfo.getAssistant());
            for (int i = 0;i < assistantArr.size();i++) {
                Long assistantId = assistantArr.getJSONObject(i).getLong("id");
                if (!assistantId.equals(courseInfo.getUserId())) {
                    BaseAppUser assistant = iBaseAppUserService.selectById(assistantId);
                    assistant.setPassword(null);
                    UserMobile assistantMobile = new UserMobile();
                    BeanUtils.copyProperties(assistant, assistantMobile);
                    assistantMobile.setPosition(1);
                    list.add(assistantMobile);
                    if (assistant.getId().equals(BaseContextHandler.getUserID()) && groupIdentity != 0) {
                        groupIdentity = 1;
                    }
                }
            }
        }
        //成员
        for (CouresOrder info : orderList) {
            UserMobile userMobile = new UserMobile();
            BaseAppUser appUser = iBaseAppUserService.selectById(info.getPayPersonId());
            appUser.setPassword(null);
            BeanUtils.copyProperties(appUser, userMobile);
            if (info.getCourseIdentity() == 1) {
                userMobile.setPosition(1);
            } else {
                userMobile.setPosition(2);
            }
            list.add(userMobile);
        }

        ret.put("list", list);
        ret.put("groupIdentity", groupIdentity);
        return new ReturnObject(0, "编辑成功", ret);
    }

    @ApiOperation("禁言成员")
    @RequestMapping(value = "/delGroupUser", method = RequestMethod.POST)
    public ReturnObject delGroupUser(@ApiParam("群id") @RequestParam Long groupId,
                                     @ApiParam("用户id") @RequestParam Long groupUserId,
                                     @ApiParam("用户类型，1：管理，2：普通成员") @RequestParam Integer type) throws Exception {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!judgeHasAdminAuth(BaseContextHandler.getUserID(), info)) {
            return new ReturnObject(1, "没有禁言成员权限");
        }
        boolean delSuccess = false;
        Long loginUserId = BaseContextHandler.getUserID();
        if (type == 1) {
            if (!info.getCrtUserId().equals(loginUserId)) {
                return new ReturnObject(1, "管理员只有群主才能禁言");
            }
            if (groupUserId.equals(info.getUserId())) {
                return new ReturnObject(1, "上课老师不能禁言");
            }
            /*
             * 禁言助理
             */
            JSONArray assistantArr = JSONArray.parseArray(info.getAssistant());
            for (int i = 0;i < assistantArr.size();i++) {
                Long assistantId = assistantArr.getJSONObject(i).getLong("id");
                if (assistantId.equals(groupUserId)) {
                    delSuccess = true;
                }
            }
        }
        if (type == 2 || delSuccess == false) {
            EntityWrapper<CouresOrder> orderEw = new EntityWrapper<>();
            orderEw.eq("state", 0).eq("course_info_id", groupId).eq("pay_person_id", groupUserId);
            CouresOrder order = orderService.selectOne(orderEw);
            if (order != null) {
                order.setGroupState(1);
                delSuccess = true;
                orderService.updateById(order);
            }
        }
        if (delSuccess == true) {
            //退出群组
            GroupModel group = new GroupModel();
            GroupMember[] members = {new GroupMember().setId(groupUserId.toString())};
            group.setId(groupId.toString());
            group.setMembers(members);
            group.setMinute(43200);
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            Result groupCreateResult = rongCloud.group.gag.add(group);
            return new ReturnObject(0, "禁言成员成功");
        } else {
            return new ReturnObject(1, "禁言成员失败");
        }
    }

    @ApiOperation("禁言成员解禁")
    @RequestMapping(value = "/delGroupUserRollback", method = RequestMethod.POST)
    public ReturnObject delGroupUserRollback(@ApiParam("群id") @RequestParam Long groupId,
                                             @ApiParam("用户id") @RequestParam Long groupUserId,
                                             @ApiParam("用户类型，1：管理，2：普通成员") @RequestParam Integer type) throws Exception {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!judgeHasAdminAuth(BaseContextHandler.getUserID(), info)) {
            return new ReturnObject(1, "没有解禁成员权限");
        }
        boolean rollSuccess = false;
        Long loginUserId = BaseContextHandler.getUserID();
        if (type == 1) {
            if (!info.getCrtUserId().equals(loginUserId)) {
                return new ReturnObject(1, "管理员只有群主才能解禁");
            }
            /*
             * 禁言助理
             */
            JSONArray assistantArr = JSONArray.parseArray(info.getAssistant());
            for (int i = 0;i < assistantArr.size();i++) {
                Long assistantId = assistantArr.getJSONObject(i).getLong("id");
                if (assistantId.equals(groupUserId)) {
                    rollSuccess = true;
                }
            }
        }
        if (type == 2 || rollSuccess == false) {
            EntityWrapper<CouresOrder> orderEw = new EntityWrapper<>();
            orderEw.eq("state", 0).eq("course_info_id", groupId).eq("pay_person_id", groupUserId);
            CouresOrder order = orderService.selectOne(orderEw);
            if (order != null) {
                order.setGroupState(0);
                rollSuccess = true;
                orderService.updateById(order);
            }
        }
        if (rollSuccess == true) {
            //群组发言解禁
            GroupModel group = new GroupModel();
            GroupMember[] members = {new GroupMember().setId(groupUserId.toString())};
            group.setId(groupId.toString());
            group.setMembers(members);
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            Result groupCreateResult = rongCloud.group.gag.remove(group);
            return new ReturnObject(0, "解禁成员成功");
        } else {
            return new ReturnObject(1, "解禁成员失败");
        }
    }

    @ApiOperation("群设置管理员")
    @RequestMapping(value = "/setAdminUser", method = RequestMethod.POST)
    public ReturnObject setAdminUser(@ApiParam("群id") @RequestParam Long groupId,
                                     @ApiParam("成员id") @RequestParam Long groupUserId) {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!info.getCrtUserId().equals(BaseContextHandler.getUserID())) {
            return new ReturnObject(1, "没有设置群管理权限");
        }

        EntityWrapper<CouresOrder> orderEw = new EntityWrapper<>();
        orderEw.eq("info.state", 0).eq("info.course_info_id", groupId).eq("info.pay_person_id", groupUserId);
        CouresOrder order = orderService.selectOne(orderEw);
        order.setCourseIdentity(1);
        orderService.updateById(order);
        return new ReturnObject(0, "设置成功");
    }

    @ApiOperation("群取消管理员身份")
    @RequestMapping(value = "/cancelAdminUser", method = RequestMethod.POST)
    public ReturnObject cancelAdminUser(@ApiParam("群id") @RequestParam Long groupId,
                                        @ApiParam("成员id") @RequestParam Long groupUserId) {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!info.getCrtUserId().equals(BaseContextHandler.getUserID())) {
            return new ReturnObject(1, "没有取消群管理权限");
        }

        boolean delSuccess = false;
        Long loginUserId = BaseContextHandler.getUserID();

        if (groupUserId.equals(info.getUserId())) {
            return new ReturnObject(1, "上课老师不能取消管理员身份");
        }
        /*
         * 判断助理身份
         */
        JSONArray assistantArr = JSONArray.parseArray(info.getAssistant());
        JSONArray newAssistantArr = new JSONArray();
        for (int i = 0;i < assistantArr.size();i++) {
            Long assistantId = assistantArr.getJSONObject(i).getLong("id");
            if (assistantId.equals(groupUserId)) {
                delSuccess = true;
            }
        }
        if (delSuccess == true) {
            return new ReturnObject(1, "助教只能删除成员，不能取消身份");
        }

        EntityWrapper<CouresOrder> orderEw = new EntityWrapper<>();
        orderEw.eq("info.state", 0).eq("info.course_info_id", groupId).eq("info.pay_person_id", groupUserId);
        CouresOrder order = orderService.selectOne(orderEw);
        order.setCourseIdentity(0);
        orderService.updateById(order);

        return new ReturnObject(0, "取消身份成功");
    }

    @ApiOperation("退群操作")
    @RequestMapping(value = "/quitGroup", method = RequestMethod.POST)
    public ReturnObject quitGroup(@ApiParam("群id") @RequestParam Long groupId) throws Exception {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (judgeHasAdminAuth(BaseContextHandler.getUserID(), info)) {
            return new ReturnObject(1, "群主管理不能退群");
        }

        EntityWrapper<CouresOrder> ew = new EntityWrapper<>();
        ew.eq("info.course_info_id", groupId).eq("info.pay_person_id", BaseContextHandler.getUserID());

        List<CouresOrder> list = orderService.selectList(ew);
        if (list.size() > 0) {
            CouresOrder order = list.get(0);
            order.setGroupState(1);
            orderService.updateById(order);

            //融云成员退出群组
            GroupModel group = new GroupModel();
            GroupMember[] members = {new GroupMember().setId(BaseContextHandler.getUserID().toString())};
            group.setId(groupId.toString());
            group.setMembers(members);
            RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
            Result groupCreateResult = rongCloud.group.quit(group);
        } else {
            return new ReturnObject(0, "退群失败");
        }
        return new ReturnObject(0, "退群成功");
    }

    @ApiOperation("解散群")
    @RequestMapping(value = "/dissolutionGroup", method = RequestMethod.POST)
    public ReturnObject dissolutionGroup(@ApiParam("群id") @RequestParam Long groupId) throws Exception {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!info.getCrtUserId().equals(BaseContextHandler.getUserID())) {
            return new ReturnObject(1, "没有解散群权限");
        }
        info.setGroupState(1);
        courseInfoService.updateById(info);

        //融云解散群
        GroupModel group = new GroupModel();
        GroupMember[] members = {new GroupMember().setId(BaseContextHandler.getUserID().toString())};
        group.setId(groupId.toString());
        group.setMembers(members);
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        Result groupCreateResult = rongCloud.group.dismiss(group);

        return new ReturnObject(0, "解散群成功");
    }

    @ApiOperation("群禁言")
    @RequestMapping(value = "/groupBan", method = RequestMethod.POST)
    public ReturnObject groupBan(@ApiParam("群id") @RequestParam Long groupId) throws Exception {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!info.getCrtUserId().equals(BaseContextHandler.getUserID())) {
            return new ReturnObject(1, "没有群禁言权限");
        }
        info.setBanState(1);
        courseInfoService.updateById(info);

        //融云群禁言
        String[] groupIds = {groupId.toString()};
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        Result groupCreateResult = rongCloud.group.ban.add(groupIds);
        logger.info("禁言群：" + groupCreateResult.getErrorMessage());
        return new ReturnObject(0, "禁言群成功");
    }

    @ApiOperation("群禁言解禁")
    @RequestMapping(value = "/groupBanRollback", method = RequestMethod.POST)
    public ReturnObject groupBanRollback(@ApiParam("群id") @RequestParam Long groupId) throws Exception {
        CourseInfo info = courseInfoService.selectById(groupId);
        if (info == null || info.getGroupState() == 1) {
            return new ReturnObject(1, "群不存在或者已解散");
        }
        if (!info.getCrtUserId().equals(BaseContextHandler.getUserID())) {
            return new ReturnObject(1, "没有群禁言管理权限");
        }
        info.setBanState(0);
        courseInfoService.updateById(info);

        //融云群禁言
        String[] groupIds = {groupId.toString()};
        RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
        Result groupCreateResult = rongCloud.group.ban.remove(groupIds);
        logger.info("禁言群：" + groupCreateResult.getErrorMessage());
        return new ReturnObject(0, "群禁言解禁成功");
    }

    @ApiOperation("添加好友")
    @RequestMapping(value = "/addFriend", method = RequestMethod.POST)
    public ReturnObject addFriend(@ApiParam("好友id") @RequestParam Long userId) {
        BaseAppUser appUser = iBaseAppUserService.selectById(userId);
        if (appUser == null) {
            return new ReturnObject(-1, "好友id不存在");
        }

        List<BaseUserFriend> list = iBaseUserFriendService.selectList(new EntityWrapper<BaseUserFriend>().eq("user_id", BaseContextHandler.getUserID()).eq("f_user_id", userId));
        if (list.size() < 1) {
            BaseUserFriend userFriend = new BaseUserFriend();
            userFriend.setCrtTime(new Date());
            userFriend.setUserId(BaseContextHandler.getUserID());
            userFriend.setFUserId(userId);
            userFriend.setUpTime(new Date());
            iBaseUserFriendService.insert(userFriend);
        }

        return new ReturnObject(0, "添加成功");
    }

    @ApiOperation("删除好友")
    @RequestMapping(value = "/delFriendByUserId", method = RequestMethod.POST)
    public ReturnObject delFriendByUserId(@ApiParam("好友id") @RequestParam Long userId) {
        EntityWrapper<BaseUserFriend> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID());
        ew.eq("f_user_id", userId);
        iBaseUserFriendService.delete(ew);
        return new ReturnObject(0, "删除成功");
    }

    @ApiOperation("更新时间")
    @RequestMapping(value = "/upTimeChat", method = RequestMethod.POST)
    public ReturnObject upTimeChat(@ApiParam("类型 1 好友 2 群") @RequestParam Integer type,
                                   @ApiParam("好友id") Long userId,
                                   @ApiParam("群id") Long groupId) {
        if (type == 1) {
            EntityWrapper<BaseUserFriend> ew = new EntityWrapper<>();
            ew.eq("user_id", BaseContextHandler.getUserID());
            ew.eq("f_user_id", userId);

            BaseUserFriend info = new BaseUserFriend();
            info.setUpTime(new Date());
            iBaseUserFriendService.update(info, ew);
        }
        if (type == 2) {
            CourseInfo courseInfo = courseInfoService.selectById(groupId);
            if (courseInfo != null) {
                courseInfo.setUpTime(new Date());
                courseInfoService.updateById(courseInfo);
            }
        }

        return new ReturnObject(0, "更新成功");
    }

    @ApiOperation("好友分页列表")
    @RequestMapping(value = "/getFriendsPage", method = RequestMethod.POST)
    public ReturnObject getFriendsPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                       @ApiParam("页数") @RequestParam(defaultValue = "1") int offset) {
        EntityWrapper<BaseUserFriend> ew = new EntityWrapper<>();
        ew.eq("user_id", BaseContextHandler.getUserID()).orderBy("up_time");
        Page<BaseUserFriend> obj = iBaseUserFriendService.selectPage(new Page<>(offset, limit), ew);

        for (BaseUserFriend info : obj.getRecords()) {
            UserMobile userMobile = new UserMobile();
            BaseAppUser appUser = iBaseAppUserService.selectById(info.getFUserId());
            appUser.setPassword(null);
            BeanUtils.copyProperties(appUser, userMobile);
            info.setUserInfo(userMobile);
        }
        return new ReturnObject(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }


}

